﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
//引用的命名空间
using Microsoft.DirectX.DirectSound;
using System.Threading;
using System.IO;
using comm;

namespace 话务台来电外放
{
    public partial class Form1 : Form
    {
        private SecondaryBuffer secBuffer;//缓冲区对象
        private Device secDev;//设备对象
        DevicesCollection dc;
        private string strConn = "";//数据库连接字符串
        private string wavPath = "";//铃声文件
        private int deviceIndex = 0;//声卡索引
        private bool bPaly = false;//是否发起通知
        private string strSql = "SELECT COUNT(*) FROM [tbl_tmpld] where DHLX=2";
        DbHelperSQL dbsql = new DbHelperSQL();
        private delegate void myDelegate(string str);//声明委托
        private Thread backgroundThread;
        Guid g;

        public Form1()
        {
            InitializeComponent();
        }

        private int Licenses()
        {
            int q = 1;
            //try
            //{
            //    string licenses = File.ReadAllText(Application.StartupPath + "/licenses");
            //    string strMac = PublicClass.GetMacAddress();
            //    string zcm = PublicClass.GetMd5Pwd(strMac + "rjPlayDevice");
            //    textBox1.Text = strMac;
            //    if (licenses == zcm)
            //    {
            //        q = 1;
            //    }

            //}
            //catch { }
            return q;
        }

        //创建用于播放的音频设备对象
        private void CreatePlayDevice()
        {

            dc = new DevicesCollection();
            string strdcName = "";
            if (dc.Count > 0)
            {
                for (int i = 0; i < dc.Count; i++)
                {
                    strdcName += i.ToString() + "." + dc[i].Description + "\r\n";
                }
                lblPlayDev.Text = strdcName;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string strXh = textBox1.Text.Trim();
            if (strXh != "")
            {
                g = dc[Convert.ToInt32(strXh)].DriverGuid;
                secDev = new Device(g);
                secDev.SetCooperativeLevel(this, CooperativeLevel.Normal);
                BufferDescription buffDes = new BufferDescription();
                buffDes.GlobalFocus = true;//设置缓冲区全局获取焦点
                secBuffer = new SecondaryBuffer(wavPath, buffDes, secDev);//创建辅助缓冲区
                secBuffer.Play(0, BufferPlayFlags.Looping);//设置缓冲区为循环播放
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (secBuffer != null)
            {
                secBuffer.Stop();
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            if (Licenses() == 0)
            {
                textBox2.Text = PublicClass.GetMacAddress();
                groupBox1.Visible = false;
            }
            else
            {
                panel1.Visible = false;
                groupBox1.Visible = false;
                strConn = dbsql.GetZy(1);
                string strDn = dbsql.GetZy(3);
                if (strDn != "0")
                {
                    strSql = "SELECT COUNT(*) FROM [tbl_tmpld] where DHLX=2 and BJHM='" + strDn + "'";
                }
                deviceIndex = Convert.ToInt32(dbsql.GetZy(2));
                wavPath = System.IO.Directory.GetCurrentDirectory() + "\\ring.wav";
                CreatePlayDevice();

                g = dc[deviceIndex].DriverGuid;
                
                backgroundThread = new System.Threading.Thread(new ThreadStart(BackgroundThread));
                backgroundThread.Start();
            }
        }

        private void BackgroundThread()
        {
            lblInfo.Text = "正在连接数据库……";
            if (dbsql.OpenRequest(strConn))
            {
                while (true)
                {
                    AgentRing();
                    Thread.Sleep(3000);
                }
            }
            else
            {
                lblInfo.Text = "数据库连接失败！";
            }
        }

        private void setRich(string str)
        {
            //lbLog 控件名
            if (this.lblInfo.InvokeRequired)
            {
                myDelegate md = new myDelegate(setRich);
                this.Invoke(md, str);
            }
            else
            {
                this.lblInfo.Text = str;
            }
        }


        private void AgentRing()
        {
            try
            {
                setRich("运行中" + DateTime.Now.ToString());
                string i = dbsql.SqlGetData(strSql, strConn);
                if (i != "0" && bPaly == false)
                {
                    secDev = new Device(g);
                    secDev.SetCooperativeLevel(this, CooperativeLevel.Normal);
                    BufferDescription buffDes = new BufferDescription();
                    buffDes.GlobalFocus = true;//设置缓冲区全局获取焦点
                    secBuffer = new SecondaryBuffer(wavPath, buffDes, secDev);//创建辅助缓冲区
                    bPaly = true;
                    secBuffer.Play(0, BufferPlayFlags.Looping);
                }
                else if (i == "0")
                {
                    if (bPaly != false)
                    {
                        secBuffer.Stop();
                        bPaly = false;
                    }
                }
            }
            catch (Exception ex)
            {
                bPaly = false;
                MessageBox.Show("外放设备异常，检查USB是否松动。" + ex.ToString());
            }

        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            DialogResult result = MessageBox.Show("是否退出？选否,最小化到托盘", "操作提示", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
            if (result == DialogResult.Yes)
            {
                this.Dispose();
                System.Environment.Exit(0);
            }
            else
            {
                e.Cancel = true;
                this.WindowState = FormWindowState.Minimized;
                this.Visible = false;
                this.notifyIcon1.Visible = true;
            }
        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (this.Visible)
            {
                this.WindowState = FormWindowState.Minimized;
                this.notifyIcon1.Visible = true;
                this.Hide();
            }
            else
            {
                this.Visible = true;
                this.WindowState = FormWindowState.Normal;
                this.Activate();
            }
        }
    }
}
